import 'package:flutter/material.dart';
import 'package:video_player/video_player.dart';
import 'package:wechat_assets_picker/wechat_assets_picker.dart';
import 'package:wechat_assets_picker_plus/src/const.dart';

import '../asset_util.dart';

// 图片视频组件
// ignore: must_be_immutable
class MediaContentDetailView extends StatelessWidget {
  // 媒体文件路径
  final List<String> srcUrls;

  // 点击媒体文件回调文件路径，当回调“”时，点击效果为“+1”
  final void Function(String) onTap;

  MediaContentDetailView({
    super.key,
    required this.srcUrls,
    required this.onTap,
  });

  // 一行最多数量
  int oneLineMaxCount = 3;

  // item间隙
  double itemSpace = 10;

  // 显示的图片
  List<String> _showUrls = [];

  late VideoPlayerController _controller;

  @override
  Widget build(BuildContext context) {
    if (srcUrls.length > oneLineMaxCount) {
      _showUrls = srcUrls;
    } else {
      _showUrls = srcUrls;
    }
    final width = MediaQuery.of(context).size.width;
    double itemW =
        (width - 4 * 16 - (oneLineMaxCount - 1) * itemSpace) / oneLineMaxCount;
    return Visibility(
      child: Padding(
        padding: const EdgeInsets.only(top: 16),
        child: Wrap(
          spacing: itemSpace,
          runSpacing: itemSpace,
          alignment: WrapAlignment.start,
          children: _showUrls.asMap().keys.map((index) {
            return _buildImageWidget(
              _showUrls[index],
              itemW,
              itemW,
              index,
            );
          }).toList(),
        ),
      ),
    );
  }

  // 构建图片组件
  Widget _buildImageWidget(String url, double w, double h, int index) {
    return Visibility(
      visible: url.isNotEmpty,
      child: GestureDetector(
        onTap: () {
          onTap(url);
        },
        child: Stack(
          children: [
            Visibility(
              visible: !_isVideoStyle(url),
              replacement: ClipRRect(
                borderRadius: BorderRadius.circular(4.0), // 设置圆角半径
                child: Container(
                  color: Colors.black,
                  width: w,
                  height: h,
                  child: Stack(
                    alignment: Alignment.center,
                    children: [
                      FutureBuilder(
                        future: _initializeVideo(url),
                        builder: (context, snapshot) {
                          if (snapshot.connectionState ==
                              ConnectionState.done) {
                            return AspectRatio(
                              aspectRatio: _controller.value.aspectRatio,
                              child: VideoPlayer(_controller),
                            );
                          } else {
                            return Image(
                              image: AssetImage(
                                  "assets/images/wechat_assets_picker_plus_placeholder_img.png",
                                  package: Constant.PACKAGE_NAME),
                            );
                          }
                        },
                      ),
                      SizedBox(
                        width: 30,
                        height: 30,
                        child: Image.asset(
                          "assets/images/wechat_assets_picker_plus_start_play.png",
                          package: Constant.PACKAGE_NAME,
                        ),
                      ),
                    ],
                  ),
                ),
              ),
              child: ClipRRect(
                borderRadius: BorderRadius.circular(4.0), // 设置圆角半径
                child: SizedBox(
                  width: w,
                  height: h,
                  child: FadeInImage(
                    fit: BoxFit.cover,
                    placeholder: AssetImage("assets/images/wechat_assets_picker_plus_placeholder_img.png",
                        package: Constant.PACKAGE_NAME),
                    image: NetworkImage(url),
                  ),
                ),
              ),
            ),
            Visibility(
              visible: false,
              child: _buildCoverView(w, h),
            ),
          ],
        ),
      ),
    );
  }

  // 构建“+1”蒙层
  _buildCoverView(double w, double h) {
    return Visibility(
      visible: srcUrls.length > oneLineMaxCount,
      child: GestureDetector(
        onTap: () {
          onTap("");
        },
        child: ClipRRect(
          borderRadius: BorderRadius.circular(4.0), // 设置圆角半径
          child: Container(
            alignment: Alignment.center,
            color: const Color.fromRGBO(1, 1, 1, 0.6),
            width: w,
            height: h,
            child: Text(
              "+${srcUrls.length - oneLineMaxCount}",
              style: const TextStyle(
                color: Colors.white,
                fontWeight: FontWeight.w500,
                fontSize: 40,
              ),
            ),
          ),
        ),
      ),
    );
  }

  // 视频样式
  bool _isVideoStyle(String url) {
    return AssetTypeUtils.parse(url) == AssetType.video;
  }

  _initializeVideo(String url) async {
    // ignore: deprecated_member_use
    final controller = VideoPlayerController.network(
      url,
    );
    await controller.initialize();
    _controller = controller;
  }
}
